package org.i1510.common.interceptor;

import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.i1510.common.annotation.RequestAddParam;
import org.i1510.common.bean.SessionUserBean;
import org.i1510.common.enums.UrlAddParamEnum;
import org.i1510.common.po.SysPop;
import org.i1510.common.service.ISysPopService;
import org.i1510.common.service.ISysUserService;
import org.i1510.common.utils.PrintWriterUtils;
import org.i1510.common.utils.SpringContextUtil;
import org.i1510.common.utils.UserUtils;
import org.i1510.common.utils.web.ResultMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class AuthAccessInterceptor extends HandlerInterceptorAdapter {

	private static Logger logger = LoggerFactory
			.getLogger(AuthAccessInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		ResultMapper mapper = ResultMapper.generateFailure();
		ISysPopService iSysPopService = (ISysPopService) SpringContextUtil.getBean("iSysPopService");
		HandlerMethod handlerM = (HandlerMethod) handler;
		String className = handlerM.getMethod().getDeclaringClass().getName();
		String methodName = handlerM.getMethod().getName();
		HttpSession session = request.getSession();
		Object userSession = session.getAttribute("userSession");
		
		Map conditions = new HashMap();
		conditions.put("docCreator", UserUtils.getSessionUserBean(request).getSysUser().getDocId());
		conditions.put("className", className);
		conditions.put("methodName", methodName);
		conditions.put("isValid", "00");
		conditions.put("docStatus", "10");
		//获取是否不用验证的权限
		List  sysPops_needless = iSysPopService.getSysUser4Pop(conditions);
		if(null != sysPops_needless && sysPops_needless.size() > 0){
			return true;
		}else{
			conditions.remove("isValid");
			conditions.put("isValid", "10");
			List  sysPops = iSysPopService.getSysUser4Pop(conditions);			
			if(null != sysPops && sysPops.size() > 0 ){
				return true;
			}else{
				mapper.appendResult("message", "您无权限,请找管理员!");
			}
		}
		
		PrintWriterUtils pr = new PrintWriterUtils();
		pr.sendPrintWriterUtils(response, mapper.toJson(), "plain");	
	
		return false;
	}

}